/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hhf.flex.ascreator.patterns;

import hhf.flex.annotations.services.AddEntities;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.util.Map;

/**
 *
 * @author utilisateur
 */
public class ASAddEntitiesPattern {

	/**
	 * Ecrit les fonctions de type "addEntity" qui permettent de persister
	 * des entités dans la base locale.
	 * @param out
	 * @param method
	 * @param argsTyped
	 * @param annotedNames
	 * @throws IOException 
	 */
	public static void writeAddEntitiesFunctions(OutputStreamWriter out, Method method, String argsTyped, Map<String, String> annotedNames) throws IOException {
		//il y a une annotation @AddEntities
		if (method.getAnnotation(AddEntities.class) != null) {
			out.write("\t\t//Fonction @AddEntities\n");
			out.write("\t\tprivate function addEntities(" + argsTyped + "):void {\n");
			AddEntities addEntities = method.getAnnotation(AddEntities.class);
			for (String entityName : addEntities.entities().split(",")) {
				if (annotedNames.get(entityName) != null) {
					out.write("\t\t\ttry {\n");
					out.write("\t\t\t\tem.persist(" + annotedNames.get(entityName) + ");\n");
					out.write("\t\t\t} catch(e:EntityExistsException) {\n");
					out.write("\t\t\t\tem.merge(" + annotedNames.get(entityName) + ");\n");
					out.write("\t\t\t}\n");
				} else {
					//TODO :  gestion de l'erreur
				}
			}
			out.write("\t\t}\n\n");
		}
	}
}
